<template>
  <div id="search">
    <van-sticky>
      <form action="/">
        <van-search
          v-model.trim="searchText"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          background="#2396Fa"
          @cancel="$router.back()"
          @focus="isShowResults = false"
        />
      </form>
    </van-sticky>
    <!-- 结果 -->
    <SearchResults :searchText="searchText" v-if="isShowResults" />
    <!-- 历史 -->
    <SearchHistory @search="onSearch" :history="history" v-else-if="!searchText" />
    <!-- 建议 -->
    <SearchSuggestion @onClickItem="onSearch" v-else :searchText="searchText" />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResults from './components/SearchResults.vue'
import SearchSuggestion from './components/SearchSuggestion.vue.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'Search',
  data () {
    return {
      searchText: '',
      isShowResults: false,
      history: getItem('HMTT-HISTORY') || []
    }
  },
  components: {
    SearchHistory,
    SearchResults,
    SearchSuggestion
  },
  watch: {
    history: {
      deep: true,
      handler () {
        setItem('HMTT-HISTORY', this.history)
      }
    }
  },
  // 定义方法
  methods: {
    onSearch (val) {
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      this.searchText = val
      this.isShowResults = true
    }
  }
}
</script>

<style scoped lang="less">
#search {
  .van-search__action {
    color: #fff;
  }
}
</style>
